// ===== 0. 全局变量 =====

const csrfToken = '{{ csrf_token }}';

// ===== 1. 播放音乐（点歌名） =====
$(function () {
    $('#musicTable').on('click', '.song-name', function () {
        const id = $(this).data('id');
        const audio = document.getElementById('player');
        const btn = document.getElementById('ctrlBtn');

        $.ajax({
            url: '/api/cover/',
            type: 'GET',
            data: { id: id },
            dataType: 'json',
            success: function (res) {
                if (res.cover) $('#coverBox').attr('src', res.cover);
                if (res.audio) {
                    audio.src = res.audio;
                    audio.load();
                    audio.play();
                    btn.src = '/static/tu/zt.png';
                } else {
                    alert('暂无音频');
                }

                // 给收藏图标赋值
                $('.love').attr('data-id', id).attr('data-loved', 'false');
            },
            error: function () { alert('获取封面失败'); }
        });
    });
});

// ===== 2. 播放/暂停按钮 =====
$('#ctrlBtn').on('click', function () {
    const audio = document.getElementById('player');
    const btn = this;
    if (audio.paused) {
        audio.play();
        btn.src = '/static/tu/zt.png';
    } else {
        audio.pause();
        btn.src = '/static/tu/bf.png';
    }
});

// ===== 3. 分类下拉菜单 =====
$('.button').on('click', function () {
    const id = $(this).data('id');
    $.ajax({
        url: '/classify/',
        type: 'GET',
        data: { id: id },
        dataType: 'json',
        success: function (res) {
            let html = '';
            if (res.musics && res.musics.length > 0) {
                for (let song of res.musics) {
                    html += `<tr>
                        <td class="song-name" data-id="${song.id}">${song.Title}</td>
                        <td>${song.author}</td>
                    </tr>`;
                }
            } else {
                html = '<tr><td colspan="2">暂无音乐</td></tr>';
            }
            $('#musicTable tbody').html(html);
        },
        error: function () { alert('加载失败'); }
    });
});

// ===== 4. 收藏/取消 =====
$('.love').on('click', function () {
    if (!isLogin) { alert('你还没登录'); return; }

    const btn = $(this);
    const musicId = btn.data('id');
    if (!musicId) { alert('请先播放一首歌'); return; }

    $.post('/like/toggle/', {
        music_id: musicId,
        csrfmiddlewaretoken: csrfToken
    }, function (res) {
        if (res.code === 0) {
            btn.attr('src', res.liked ?
                '/static/tu/heart-full.png' :
                '/static/tu/heart-empty.png');
            btn.attr('data-loved', res.liked);
        } else {
            alert(res.msg);
        }
    });
});